import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_account_book/generated/l10n.dart';
import 'package:flutter_account_book/pages/pay/logic.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';

class PayPage extends StatelessWidget {
  const PayPage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(PayLogic());
    return Scaffold(
        appBar: AppBar(
          title: Text('支付方式'),
          actions: [IconButton(onPressed: () {}, icon: const Icon(Icons.add))],
        ),
        body: Obx(() => ReorderableListView.builder(
            onReorder: (oldIndex, newIndex) async {
              final item = logic.state.list.removeAt(oldIndex);
              if (newIndex > logic.state.list.length) {
                newIndex = logic.state.list.length;
              }
              logic.state.list.insert(newIndex, item);
              var minIndex = min(oldIndex, newIndex);
              for (var i = minIndex; i < logic.state.list.length; i++) {
                var item = logic.state.list[i];
                item.order = i;
                await item.save();
              }
            },
            itemBuilder: (context, index) {
              final payMethod = logic.state.list[index];
              return Container(
                  key: ValueKey(payMethod.id),
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(color: Colors.grey, width: 0.5))),
                  child: Slidable(
                      endActionPane: ActionPane(
                        motion: const ScrollMotion(),
                        children: [
                          SlidableAction(
                              onPressed: (BuildContext context) {},
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                              label: S.current.delete),
                        ],
                      ),
                      child: InkWell(
                        onTap: () async {},
                        child: ListTile(
                            title: Text(payMethod.name),
                            leading: payMethod.type == 0
                                ? Image.asset(payMethod.iconPath ?? "",
                                    width: 30, height: 30)
                                : null,
                            trailing: const Icon(Icons.menu)),
                      )));
            },
            itemCount: logic.state.list.length)));
  }
}
